package com.fz.us.oa.web.controller.main.company;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.Result;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.company.entity.*;
import com.fz.us.admin.company.service.DepartmentService;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.PowerService;
import com.fz.us.admin.company.service.UserService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 控制器 - 职位信息
 * ============================================================================
 * 版权所有 2016 。
 *
 * @author fallenpanda
 * @version 1.0 2016-08-16 。
 * ============================================================================
 */
@Controller
@RequestMapping(value = "/main/duty")
public class DutyController extends BaseController {

    private static final long serialVersionUID = -1617028717254551682L;

    @Autowired
    private UserService userService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private PowerService powerService;
    @Autowired
    private DutyService dutyService;

    /**
     * 新建页面
     */
    @RequestMapping(value = "create", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String create(@CurrentUser User user, Model model,
                         @RequestParam(required = false) String departmentId) {

        model.addAttribute("departmentId", departmentId);
        return "/main/company/duty_input";
    }

    /**
     * 编辑页面
     */
    @RequestMapping(value = "update/{keyId}", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String update(@CurrentUser User user, Model model,
                         @PathVariable String keyId) {

        model.addAttribute("keyId", keyId);
        return "/main/company/duty_input";
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user,
                       @RequestParam(required = false) String keyId,
                       String powerId,
                       String userId,
                       Duty duty) {
        // 必填校验
        if (StringUtils.isBlank(powerId)) {
            return resultService.fail("职权不能为空");
        }
        if (StringUtils.isBlank(userId)) {
            return resultService.fail("成员不能为空");
        }
        // 职权
        Power power = powerService.get(powerId);
        if (power != null) {
            duty.setPower(power);
        }
        // 成员
        User member = userService.get(userId);
        if (member != null) {
            duty.setUser(member);
        }

        if (StringUtils.isBlank(keyId)) {// 保存
            return ajaxJson(dutyService.createEntity(user, duty));
        } else {// 修改
            return ajaxJson(dutyService.updateEntity(user, keyId, duty));
        }
    }

    /**
     * 初始化表单
     */
    @RequestMapping(value = "init", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object init(@CurrentUser User user,
                       @RequestParam(required = false) String departmentId) {
        Duty duty = new Duty();
        if (StringUtils.isNotBlank(departmentId)) {
            Department department = departmentService.get(departmentId);
            if (department != null) {
                Power power = new Power();
                power.setDepartment(department);
                duty.setPower(power);
            }
        }

        Map<String, Object> dataMap = dutyService.getDetailMap(duty);

        Result result = resultService.success("", dataMap);

        return ajaxJson(result);
    }

    /**
     * 获取详情
     */
    @RequestMapping(value = "read/{keyId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object read(@CurrentUser User user,
                       @PathVariable String keyId) {
        Duty duty = dutyService.get(keyId);
        if (duty == null){
            duty = new Duty();
        }

        Map<String, Object> dataMap = dutyService.getDetailMap(duty);

        Result result = resultService.success("", dataMap);

        return ajaxJson(result);
    }

    /**
     * 操作
     */
    @RequestMapping(value = "method/{method}/{keyId}", method = RequestMethod.POST)
    public Object method(@CurrentUser User user,
                         @PathVariable String method,
                         @PathVariable String keyId) {
        Result result = dutyService.methodEntity(user, method, keyId);

        return ajaxJson(result);
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list_department", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list_department(@CurrentUser User user,
                                               String departmentId,
                                               JqGridPager pager,
                                               @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();

        Department department = departmentService.get(departmentId);

        // 排序
        /*
        Order order = null;
        if (StringUtils.isNotBlank(pager.getSidx()) && StringUtils.isNotBlank(pager.getSord())) {
            order = Order.order(pager.getSidx(), SearchEnum.OrderType.valueOf(pager.getSord()));
        }
        List<Rule> rules = getSearchFilterRules(pager.getSearch(), filters);
        */
        SearchResultPaging searchResult = dutyService.pagingDuty(null,null,null, company, department, BaseEnumManager.StateEnum.Enable);
        List<Duty> dutyList = searchResult.getList();

        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();

        for (Duty entity : dutyList) {
            Map<String, Object> map = dutyService.getListMap(entity);
            dataRows.add(map);
        }

        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());

        return data;
    }

}
